package io.github.lee.core.ui.ba

import android.graphics.drawable.Drawable
import android.util.Log
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import coil.load
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.transform.Transformation

@BindingAdapter(
    value = ["load_url", "crossfade_time", "placeholder_res", "error_res"],
    requireAll = false
)
fun ImageView.coilBindingLoad(
    url: String?,
    crossfade: Int? = null,
    placeholder: Drawable? = null,
    error: Drawable? = null
) {
    this.coilLoad(url, crossfade, placeholder, error)
}


fun ImageView.coilLoad(
    url: String?,
    crossfade: Int? = null,
    placeholder: Drawable? = null,
    error: Drawable? = null,
    vararg transformations: Transformation
) {
    if (url.isNullOrEmpty()) {
        if (null != error) {
            this.setImageDrawable(error)
        }
        return
    }
    Log.e("Image Url", "load url is : $url")
    this.load(url) {
        if (null != crossfade) {
            crossfade(true)
            crossfade(crossfade)
        }
        listener(object : ImageRequest.Listener {
            override fun onError(request: ImageRequest, result: ErrorResult) {
                Log.e("Error", "${request.data} load error : ${result.throwable}")
            }
        })
        if (null != placeholder) {
            placeholder(placeholder)
        }
        if (null != error) {
            error(error)
        }
        transformations(*transformations)
    }
}

